from django.db.models.signals import pre_save
from django.dispatch import receiver
from .models import BookInstance

@receiver(pre_save, sender=BookInstance)
def update_borrow_count(sender, instance, **kwargs):
    """
    Update the borrow count of a book when its instance status changes to 'On loan'.
    """
    # We only care about existing instances changing status.
    if instance.pk:
        try:
            # Get the state of the instance from the database before the save.
            old_instance = BookInstance.objects.get(pk=instance.pk)
            # Check if the status is changing from something else to 'On loan'.
            if old_instance.status != 'o' and instance.status == 'o':
                # Increment the borrow count of the associated book.
                instance.book.borrow_count += 1
                instance.book.save()
        except BookInstance.DoesNotExist:
            # This can happen if the instance is being created, so we just pass.
            pass
